package com.wish.wishhouse_foreclosure.service.impl;

import com.github.pagehelper.PageInfo;
import com.wish.wishhouse_foreclosure.entity.TSfContract;
import com.wish.wishhouse_foreclosure.mapper.TSfContractMapper;
import com.wish.wishhouse_foreclosure.service.ITSfContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dto.houseResourceDto.TSfContractDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.wishhouse_foreclosure.entity.*;
import com.wish.wishhouse_foreclosure.enums.*;
import com.wish.wishhouse_foreclosure.enums.PayPlanZdType;
import com.wish.wishhouse_foreclosure.mapper.*;
import com.wish.wishhouse_foreclosure.service.ISysUserService;
import com.wish.wishhouse_foreclosure.service.ITMSequenceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.wishhouse_foreclosure.service.ITSfContractService;
import com.wish.wishhouse_foreclosure.service.feign.SystemService;
import dto.houseForeclosureDto.*;
import dto.response.ResponseSearchSfsDto;
import dto.systemDto.SysUserDto;
import enums.BusinessCostTypesEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import utils.SerialType;

import java.math.BigDecimal;
import java.util.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wish.wishhouse_foreclosure.entity.*;
import com.wish.wishhouse_foreclosure.mapper.*;
import com.wish.wishhouse_foreclosure.service.ITSfContractService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wish.wishhouse_foreclosure.service.ITbHouseInfoService;


import dto.houseForeclosureDto.RequestDetailSfContractDto;
import dto.houseForeclosureDto.RequestTerminalSfContractDto;
import dto.houseForeclosureDto.ResponseDetailSfContractDto;
import dto.houseForeclosureDto.TsfContractDto;


import org.slf4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangshuxin
 * @since 2021-03-31
 */
@Service
@Slf4j
public class TSfContractServiceImpl extends ServiceImpl<TSfContractMapper, TSfContract> implements ITSfContractService {


    @Autowired
    private TMOwnerMapper tmOwnerMapper;
    @Autowired
    private TbHouseInfoMapper tbHouseInfoMapper;
    @Autowired
    private ITMSequenceService itmSequenceService;
    @Autowired
    private TCwReceiptPlanMapper tCwReceiptPlanMapper;
    @Autowired
    private TCwPaymentPlanMapper tCwPaymentPlanMapper;
    @Autowired
    private TMAttachmentMapper tmAttachmentMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private SystemService systemService;

    @Autowired
    private TSfContractMapper tSfContractMapper;
    @Override
    public PageInfo<TSfContract> selects(TSfContractDto tSfContractDto) {
        List<TSfContract> list=tSfContractMapper.selects(tSfContractDto);
        return new PageInfo<TSfContract>(list);
    }


    @Autowired
    ITbHouseInfoService iTbHouseInfoService;

    @Autowired
    TSfTerminationMapper tSfTerminationMapper;
    @Autowired
    TSfFinalStatementDetailMapper tSfFinalStatementDetailMapper;



    @Autowired
    TbRoomInfoMapper tbRoomInfoMapper;



    @Override
    public List<TSfContract> selectPageVo(TsfContractDto tsfContractDto) {
        return baseMapper.selectPageVo(tsfContractDto);
    }

    @Override
    public void saveSfContract(RequestDetailSfContractSaveDto requestDetailSfContractSaveDto) throws Exception {
        log.info("saveSfContract录入/续约收房合同 Start...");
        log.info("保存业主信息");
        Date nowTime = new Date();
        SysUserDto user = systemService.getBusinessIdByUserId(requestDetailSfContractSaveDto.getUsername());
        requestDetailSfContractSaveDto.setLoginUserId(user.getUserId());
        Long loginUserId = user.getUserId();
        TMOwner mOwnerEntity = new TMOwner();
        BeanUtils.copyProperties(requestDetailSfContractSaveDto,mOwnerEntity);
         mOwnerEntity.setContractId(requestDetailSfContractSaveDto.getSfContractId());
        mOwnerEntity.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
        mOwnerEntity.setIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
        mOwnerEntity.setMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        mOwnerEntity.setAddress(requestDetailSfContractSaveDto.getOwnerContactAddress());
        mOwnerEntity.setUrgMobile(requestDetailSfContractSaveDto.getSignUserEmergencyPhone());
        //mOwnerEntity.setBankCard(requestDetailSfContractSaveDto.getBankCard());
       // mOwnerEntity.setBankUserName(requestDetailSfContractSaveDto.getBankUserName());
        mOwnerEntity.setBankOpen(requestDetailSfContractSaveDto.getBankOpen());
        mOwnerEntity.setBankName(requestDetailSfContractSaveDto.getBankName());
        //mOwnerEntity.setBankUserIdCard(requestDetailSfContractSaveDto.getBankUserIdCard());
        mOwnerEntity.setAccountType(requestDetailSfContractSaveDto.getAccountType());//银行账户类型（对公账户、对私账户）
        mOwnerEntity.setBankCardNumber(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        mOwnerEntity.setAccountName(requestDetailSfContractSaveDto.getAccountName());//账户名称（对公为企业名称，对私为姓名）
        mOwnerEntity.setBankBranchCodeLh(requestDetailSfContractSaveDto.getBankBranchCodeLh());//联行行号（手输，对公必须）
        mOwnerEntity.setBankAccountProvince(requestDetailSfContractSaveDto.getBankAccountProvince());//开户行所在省ID
        // 共通设定
        mOwnerEntity.setCreateUserid(loginUserId);
        mOwnerEntity.setCreateTime(nowTime);
         mOwnerEntity.setUpdateUserid(loginUserId);
        mOwnerEntity.setUpdateTime(nowTime);
        tmOwnerMapper.insert(mOwnerEntity);

        log.info("保存收房合同信息");
        // 获取房产信息
        TbHouseInfo houseInfo = tbHouseInfoMapper.getHouseInfoByHouseId(requestDetailSfContractSaveDto.getHouseId());
        TSfContract tSfContract = new TSfContract();
        if (requestDetailSfContractSaveDto.getSignWithOwner() == null) {
            requestDetailSfContractSaveDto.setSignWithOwner(1);
        }
        // 签约人是否为业主
        if (requestDetailSfContractSaveDto.getSignWithOwner().equals(0)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getOwnerName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getOwnerIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getOwnerMobile());
        } else if (requestDetailSfContractSaveDto.getSignWithOwner().equals(1)) {
            tSfContract.setSignUserName(requestDetailSfContractSaveDto.getSignUserName());
            tSfContract.setSignUserIdCard(requestDetailSfContractSaveDto.getSignUserIdCard());
            tSfContract.setSignUserMobile(requestDetailSfContractSaveDto.getSignUserMobile());
        }
        BeanUtils.copyProperties(requestDetailSfContractSaveDto, tSfContract);

        String contractNo = "";
        try {
            // contractNo = itmSequenceService.getSerialNumber(SerialType.SHOUFANGHETONG);
            contractNo =UUID.randomUUID().toString();
        } catch (Exception e) {
            log.info("-----出房合同编号获取失败-----");
            throw e;
        }
        tSfContract.setHouseId(requestDetailSfContractSaveDto.getHouseId());
        tSfContract.setSfContractNo(contractNo);
        // 业主ID
        tSfContract.setOwnerId(mOwnerEntity.getId());
        // 合同开始时间
        tSfContract.setLeaseStartTime(requestDetailSfContractSaveDto.getLeaseStartTime());
        // 合同结束时间
        tSfContract.setLeaseEndTime(requestDetailSfContractSaveDto.getLeaseEndTime());
        // 签约时间
        tSfContract.setConSignTime(nowTime);
        // 录入日期
        tSfContract.setConInfoTime(nowTime);
        // 审核日期
        tSfContract.setConAudTime(nowTime);
        // 押金
        tSfContract.setDepositMoney(requestDetailSfContractSaveDto.getDepositMoney());
        // 合同录入人
        tSfContract.setOperId(loginUserId);
        // 收房人ID
        tSfContract.setSfUserId(loginUserId);
        // 是否未签约人
        tSfContract.setSignWithOwner(requestDetailSfContractSaveDto.getSignWithOwner());
        // 收房人姓名
        tSfContract.setSfUserName(user.getUsername());
        // 合同状态（1，草稿。2，已提交。3，已解约。4，已结束。9:作废）
        tSfContract.setStatus(ContractStateEnum.SUBMITED.getIndex());

        Integer houseLeaseType = 3;
        if (houseInfo.getReserve1() !=null) {
            if (houseInfo.getReserve1() == 1) {
                houseLeaseType = 1;
            } else if (houseInfo.getReserve1() == 2) {
                houseLeaseType = 2;
            }
        }
        tSfContract.setHouseLeaseType(houseLeaseType);
        // 续约状态（0，未续约。1，已续约）
        tSfContract.setXyStatus(false);
        tSfContract.setBankCard(requestDetailSfContractSaveDto.getBankCardNumber());//银行卡号
        // 共通设定项
        tSfContract.setDelFlg(false);
        tSfContract.setUpdateUserid(loginUserId);
        tSfContract.setUpdateTime(nowTime);
        tSfContract.setCreateUserid(loginUserId);
        tSfContract.setCreateTime(nowTime);

        tSfContract.setBusinessId(user.getBusinessId());
        baseMapper.insert(tSfContract);
        // 续约时
        if (tSfContract.getLastContractId() != null) {
            // 获取原合同
            TSfContract sfEntity = baseMapper.selectById(tSfContract.getLastContractId());
            // 更新原合同的续约状态
            sfEntity.setXyStatus(true);
            sfEntity.setUpdateTime(new Date());
            sfEntity.setUpdateUserid(loginUserId);
            sfEntity.setDepositMoney(new BigDecimal("0"));
            baseMapper.updateById(sfEntity);
            // 生成收款计划 - 支付原合同 - 押金
            TCwReceiptPlan rec = new TCwReceiptPlan();
            String recNo = "";
            try {
               // recNo = itmSequenceService.getSerialNumber(SerialType.SHOUKUANJIHUA);
                recNo = UUID.randomUUID().toString();
            } catch (Exception e) {
                log.info("-----收款计划编号获取失败-----");
                throw e;
            }
            // 收款计划编号
            rec.setReceiptOrderNo(recNo);
            // 商户ID
            rec.setBusinessId(sfEntity.getBusinessId().longValue());
            // 收房合同ID
            rec.setContractId(sfEntity.getId());
            // 收房合同单号
            rec.setContractNo(sfEntity.getSfContractNo());
            // 合同类型：收房合同
            rec.setContractType(ContractTypeEnum.SF.getIndex());
            // 楼盘ID
            rec.setPremiseId(houseInfo.getPremisesId().longValue());
            // 小区
            rec.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
            // 业主ID
            rec.setOwnerId(sfEntity.getOwnerId());
            // 业主名称
            rec.setOwnerName(sfEntity.getOwnerName());
            // 收款类型
            rec.setReceiptType(ReceiptTypeEnum.FZ.getIndex());
            // 收款状态
            rec.setSkStatus(SkStatusEnum.YSK.getIndex());
            // 账单类型
            rec.setBillType(CollectionPlanZdType.PTZD.getIndex());
            // 款项
            rec.setItemType(BusinessCostTypesEnum.YAJIN.getIndex());
            // 支付金额（应收金额）合计
            BigDecimal depositMoney = requestDetailSfContractSaveDto.getDepositMoney();
            rec.setPaymentAmount(new BigDecimal(Math.abs(depositMoney.doubleValue()) + ""));
            // 租金 //收房合同租金
            rec.setRentalPrice(tSfContract.getMonthRent());
            // 账期开始日
            rec.setPaymentDaysBegin(nowTime);
            // 操作人
            rec.setOperationUser(user.getUsername());// 操作人
            // 备注
            rec.setRemark(requestDetailSfContractSaveDto.getRemark());
            // 共通
            rec.setDelFlg(false);
            rec.setCreateTime(nowTime);
            rec.setUpdateTime(nowTime);
           rec.setCreateUserid(loginUserId);
             rec.setUpdateUserid(loginUserId);
            tCwReceiptPlanMapper.insert(rec);
        }
        // 添加房产附件信息
        log.info("保存附件信息");
        /**
         * 附件保存： ① 业务对象ID,附件所属对应的业务数据ID，比如：合同/协议ID ②
         * 附件所属区分,"10：收房合同，11：收房解约协议，20：出房合同，21：出房解约协议" ③
         * 附件类型,"1:房产证，2：收房合同，3：业主身份证，4：代理人身份证，5：银行卡信息，
         * 6：委托书，7：解约合同，8：租赁合同，9：客户身份证，10：物业交割单，99：其他"
         */
        // 业务对象ID
        Long relationId = tSfContract.getId();
        // 附件所属区分
        Integer relationType = AttachmentRelationTypeEnum.SFHT.getIndex();
        // 保存房产证件
        saveAttachement(relationId, relationType, AttachmentTypeEnum.FCZ.getIndex(),
                requestDetailSfContractSaveDto.getHouseDocumentPhotos(), loginUserId);
        // 保存收房合同
        saveAttachement(relationId, relationType, AttachmentTypeEnum.SFHT.getIndex(),
             requestDetailSfContractSaveDto.getContractPhotos(),  loginUserId);
        // 保存业主身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YZSFZ.getIndex(), requestDetailSfContractSaveDto.getCardPhotos(), loginUserId);
        // 代理人身份证
        saveAttachement(relationId, relationType, AttachmentTypeEnum.DLRSFZ.getIndex(),
                requestDetailSfContractSaveDto.getAgentCardPhotos(),  loginUserId);
        // 银行卡信息
        saveAttachement(relationId, relationType, AttachmentTypeEnum.YHKXX.getIndex(),
               requestDetailSfContractSaveDto.getBankCardInformationPhotos(),  loginUserId);
        // 委托书
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WTS.getIndex(),
                requestDetailSfContractSaveDto.getAttorneyPhotos(), loginUserId);
        // 保存物业交割单
        saveAttachement(relationId, relationType, AttachmentTypeEnum.WYJGD.getIndex(),
                requestDetailSfContractSaveDto.getPropertyDeliverys(),  loginUserId);
        // 保存其他
        saveAttachement(relationId, relationType, AttachmentTypeEnum.QT.getIndex(),
                requestDetailSfContractSaveDto.getOtherPhotos(),  loginUserId);
        log.info("保存附件信息End.");
        log.info("保存付款计划Start...");

        List<CwPaymentPlanDto> payPlan = requestDetailSfContractSaveDto.getPayMentltems();
        if (payPlan != null) {
            for (CwPaymentPlanDto cwPaymentPlanDto : payPlan) {
                TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
                BeanUtils.copyProperties(cwPaymentPlanDto, tCwPaymentPlan);
                // 付款计划编号
                String payOrderNo = "";
                try {
                    // payOrderNo = itmSequenceService.getSerialNumber(SerialType.FUKUANJIHUA);
                    payOrderNo= UUID.randomUUID().toString();
                } catch (Exception e) {
                    log.info("-----出房合同编号获取失败-----");
                    throw e;
                }
                tCwPaymentPlan.setPayNumber(cwPaymentPlanDto.getPayNumber());
                tCwPaymentPlan.setPayOrderNo(payOrderNo);
                // 商户ID
                tCwPaymentPlan.setBusinessId(user.getBusinessId());
                // 收房合同ID
                tCwPaymentPlan.setContractId(tSfContract.getId());
                // 收房合同编号
                tCwPaymentPlan.setContractNo(tSfContract.getSfContractNo());
                // 合同类型（收房合同）
                tCwPaymentPlan.setContractType(ContractTypeEnum.SF.getIndex());
                // 楼盘id
                if (!houseInfo.equals(null)) {
                    tCwPaymentPlan.setPremiseId(new Long(houseInfo.getPremisesId()));
                }
                // 楼盘名称(同小区名称)
                tCwPaymentPlan.setPremiseName(requestDetailSfContractSaveDto.getPremiseName());
                // 业主ID
                tCwPaymentPlan.setOwnerId(requestDetailSfContractSaveDto.getOwnerId());
                // 业主姓名
                tCwPaymentPlan.setOwnerName(requestDetailSfContractSaveDto.getOwnerName());
                // 账单类型
                tCwPaymentPlan.setBillType(PayPlanZdType.PTZD.getIndex());
                // 付款类型
                tCwPaymentPlan.setPayType(PaymentTypeEnum.SFFK.getIndex());
                // 付款状态
                tCwPaymentPlan.setPayState(cwPaymentPlanDto.getSkStatus());
                // 操作人
                tCwPaymentPlan.setOperationUser(user.getUsername());
                // 共通设定
                tCwPaymentPlan.setCreateUserid(loginUserId);
                tCwPaymentPlan.setCreateTime(nowTime);
                tCwPaymentPlan.setUpdateUserid(loginUserId);
                tCwPaymentPlan.setUpdateTime(nowTime);
                tCwPaymentPlan.setItemType(cwPaymentPlanDto.getItemType());
                tCwPaymentPlanMapper.insert(tCwPaymentPlan);
            }
        }
        log.info("saveSfContract录入/续约收房合同 End.");
    }



    /**
     * 保存附件信息
     *
     * @param relationId
     *            业务对象ID
     * @param relationType
     *            附件所属区分
     * @param attachmentType
     *            附件类型
     * @param urls
     *            附件项目url
     * @param userId
     *            操作人id
     */
    private void saveAttachement(Long relationId, Integer relationType, Integer attachmentType, String[] urls,
                                 Long userId) {
        log.info("附件开始保存");
        if (urls != null) {
            for (String url : urls) {
                if (StringUtils.isEmpty(url)) {
                    continue;
                }
                TMAttachment mAttachmentEntity = new TMAttachment();
                mAttachmentEntity.setRelationId(relationId);
                mAttachmentEntity.setRelationType(relationType);
                // 附件类型
                mAttachmentEntity.setAttachmentType(attachmentType);
                // 图片路径
                mAttachmentEntity.setUrl(url);
                // 共通设定项
                mAttachmentEntity.setUpdateUserid(userId);
                mAttachmentEntity.setUpdateTime(new Date());
                mAttachmentEntity.setCreateUserid(userId);
                mAttachmentEntity.setCreateTime(new Date());
                tmAttachmentMapper.insert(mAttachmentEntity);
            }

        }
        log.info("附件保存成功+++++++++++++++++++++++");
    }

    @Override
    public List<ResponseSearchSfsDto> listSfByXy(RequestSearchSfsDto requestSearchSfsDto) {
        log.info("listSfByXy查询收房合同查询处理Start...");
        log.info("----查询收房合同查询详情入参：{}", JSON.toJSONString(requestSearchSfsDto));
        List<ResponseSearchSfsDto> recordList = baseMapper.searchSfListByXy(requestSearchSfsDto);
        // 设置分页结果
        log.info("----输出结果：{}", JSON.toJSONString(recordList));
        log.info("listSfByXy查询收房合同查询处理End.");
        return recordList;
    }

    @Override
    public  List<TSfContract> searchSfAllNotDissolution(TsfContractDto tsfContractDto) {
        return baseMapper.searchSfAllNotDissolution(tsfContractDto);

    }

    @Override
    public ResponseDetailSfContractDto detailSfContractB(RequestDetailSfContractDto requestDetailSfContractDto) {

        return baseMapper.selectSearchById(requestDetailSfContractDto);

    }

//    @Override
//    public void terminalSfContract(RequestTerminalSfContractDto terminalSfContractDto) {
//
//
//
//    }





//	================================  ================================   ================================ ===================== ===========   st

    /**
     *
     * @Description：收房合同解约录入
     * @param @param
     *            requestTerminalSfContractDto 参数
     * @throws Exception
     * @return返回值说明
     */
    @Override
    @Transactional
    public void terminalSfContract(RequestTerminalSfContractDto requestTerminalSfContractDto) throws Exception {

        System.out.println("terminalSfContract处理Start===============================================99999888888...");

//
//        System.out.println("入参88888888888888888"+requestTerminalSfContractDto);
//        List<RoomInfoEntity> list = tbRoomInfoMapper.searchById(requestTerminalSfContractDto.getHouseId());  //***1
//        System.out.println("==================================================================998***1 end");
//        int a = 0;
//        for (RoomInfoEntity roomInfoEntity : list) {
//            Integer state = roomInfoEntity.getStatus();
//            if (state != 2) {
//                a++;
//            }
//        }

//        if (a == list.size()) {     //if (a == list.size())  st


        Date nowDate = new Date();

        TSfTermination sfTerminationEntity = new TSfTermination();  //&&&  装值实体1

//政前台解约了一条合同输出这两个为null
//            // 商户id
//            sfTerminationEntity.setBusinessId(requestTerminalSfContractDto.getBusinessId());
//            // 部门id
//            sfTerminationEntity.setDeptId(requestTerminalSfContractDto.getDeptId());

//			try {
//				sfTerminationNo = sequenceService.getSerialNumber(SerialType.SHOUFANGJIEYUE);
//			} catch (Exception e) {
//				logger.info("-----收房解约合同编号获取失败-----");
//				throw e;
//			}


//        id	主键id

//        business_id	商户ID              不甩设置
//        dept_id	部门ID                          不甩设置
//        dept_no	部门编号                    不甩设置

//        sf_termination_no	解约协议编号
        // 获取解约协议编号
        String sfTerminationNo = "";
        int random = (int) ((Math.random()*9+1)*1000);
        sfTerminationNo = "解约协议编号"  + random;
        sfTerminationEntity.setSfTerminationNo(sfTerminationNo);
//        out_termination_no	外部协议编号（线下  sfTerminationEntity.setSfTerminationNo(sfTerminationNo);解约协议号）                      不甩设置

//        sf_contract_id	收房合同id
        sfTerminationEntity.setSfContractId(requestTerminalSfContractDto.getId());
//        sf_contract_no	收房合同号
        sfTerminationEntity.setSfContractNo(requestTerminalSfContractDto.getSfContractNo());
//        premise_id	楼盘ID

        // 获取楼盘信息
        TbHouseInfo infoByHouseId = iTbHouseInfoService
                .getHouseInfoByHouseId(requestTerminalSfContractDto.getHouseId());

        System.out.println("==================================================================998***1-2 end"+infoByHouseId);// 获取楼盘信息

        // 楼盘ID
        try {
            sfTerminationEntity.setPremiseId(infoByHouseId.getPremisesId().longValue());
        } catch (Exception e) {
            throw e;
        }


//        premise_name	小区(使用楼盘名)TerminalSfContract
        sfTerminationEntity.setPremiseName(requestTerminalSfContractDto.getPremiseName());
//                house_id	房产编号
        sfTerminationEntity.setHouseId(requestTerminalSfContractDto.getHouseId());
//        house_name	房产信息
        sfTerminationEntity.setHouseName(requestTerminalSfContractDto.getHouseName());
//        cq_address	产权地址
        sfTerminationEntity.setCqAddress(requestTerminalSfContractDto.getCqAddress());
//        house_zs_no	房产证书编号
        sfTerminationEntity.setHouseZsNo(requestTerminalSfContractDto.getHouseZsNo());
//        owner_name	业主姓名
        sfTerminationEntity.setOwnerName(requestTerminalSfContractDto.getOwnerName());
//        owner_mobile	业主手机号
        sfTerminationEntity.setOwnerMobile(requestTerminalSfContractDto.getOwnerMobile());
//        sign_user_name	签约人(甲方)
        sfTerminationEntity.setSignUserName(requestTerminalSfContractDto.getSignUserName());
//                sign_user_mobile	签约人手机号
        sfTerminationEntity.setSignUserMobile(requestTerminalSfContractDto.getSignUserMobile());
//        wyjg_date	物业交割时间
        sfTerminationEntity.setWyjgDate(requestTerminalSfContractDto.getWyjgDate());
//        termination_type	解约类型（1：合同到期）（2：业主提前解约）（3：我方退租解约）（4：其他）
        sfTerminationEntity.setTerminationType(requestTerminalSfContractDto.getTerminationType());
//        ter_agr_type	解约类型其他： 解约类型为其他的时后保存使用                           不甩设置
//        accounts_receivable	结算合计,为负数的时候，应退（字段废除）                       不甩设置

//        final_statement	结算合计，为正应收， 为负数的时候是应退
        sfTerminationEntity.setFinalStatement(requestTerminalSfContractDto.getFinalStatement());
//        termination_date	解约日期（协议签订日期，暂时同录入日期一样）
        sfTerminationEntity.setTerminationDate(nowDate);
//        real_termination_date	合同实际截止日（预留字段，暂时用解约日期）
        sfTerminationEntity.setRealTerminationDate(nowDate);
//        audit_date	审核日期（目前无审核，暂时用录入日期）
        sfTerminationEntity.setAuditDate(nowDate);
//        input_user_id	录入人ID
        sfTerminationEntity.setInputUserId(requestTerminalSfContractDto.getLoginUserId());
//        input_user_name	录入人姓名
//        sfTerminationEntity.setInputUserName(requestTerminalSfContractDto.getLoginUser().getUsername());
        sfTerminationEntity.setInputUserName("暂定aa");
//        input_date	录入日期
        sfTerminationEntity.setInputDate(nowDate);
//        remark	备注
        sfTerminationEntity.setRemark(requestTerminalSfContractDto.getRemark());

//        reserve1	预留字段1   不甩设置
//        reserve2	预留字段2  不甩设置
//        reserve3	预留字段3  不甩设置
//        reserve4	预留字段4  不甩设 置
//        reserve5	预留字段5  不甩设置

//        统一设置*4
//        del_flg	删除标识 0：未删除， 1：删除
//        create_userid	创建用户id
//        create_time	创建时间
//        update_userid	更新用户id
//        update_time	更新时间
        sfTerminationEntity.setDelFlg(false);
//        sfTerminationEntity.setCreateUserid(requestTerminalSfContractDto.getLoginUserId());
//        sfTerminationEntity.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
        sfTerminationEntity.setCreateUserid(new Long(2));
        sfTerminationEntity.setUpdateUserid(new Long(2));
        sfTerminationEntity.setCreateTime(nowDate);
        sfTerminationEntity.setUpdateTime(nowDate);

        System.out.println("88877"+sfTerminationEntity);

        tSfTerminationMapper.insert(sfTerminationEntity); //***2   ("保存解约协议");
            System.out.println("==================================================================998***2 end");


//
//            logger.info("解约结算明细处理");
//            // 应收
            double recCount = 0;
//            // 应付
            double payCount = 0;
            String json = requestTerminalSfContractDto.getStatementDetailJson();
        TSfFinalStatementDetail sfDetail = null;    //&&&  装值实体2
//
//            try {
                JSONArray parseArray = JSONObject.parseArray(json);


                for (Object obj : parseArray) {
                    sfDetail = new TSfFinalStatementDetail();
                    JSONObject parseObject = JSONObject.parseObject(obj.toString());
                    // 商户ID
                    sfDetail.setBusinessId(requestTerminalSfContractDto.getBusinessId());
                    // 解约协议Id
                    sfDetail.setTSfTerminationId(sfTerminationEntity.getId());
                    // 解约协议编号
                    sfDetail.setSfTerminationNo(sfTerminationEntity.getSfTerminationNo());
                    // 收房合同ID
                    sfDetail.setSfContractId(requestTerminalSfContractDto.getId());
                    // 收房合同编号
                    sfDetail.setSfContractNo(requestTerminalSfContractDto.getSfContractNo());
                    // 收付类型 1:应退 2：应收 json类型
                    sfDetail.setDealType(Integer.parseInt(parseObject.get("dealType").toString()));
                    // json 款项 押金水电等
                    sfDetail.setItemType(Integer.parseInt(parseObject.get("itemType").toString()));
                    // json 金额
                    sfDetail.setAmount(new BigDecimal(parseObject.get("amount").toString()));
                    // json 备注
                    sfDetail.setRemark(parseObject.get("detailRemark").toString());
                    // 共通
//                    sfDetail.setCreateUserid(requestTerminalSfContractDto.getLoginUserId());
//                    sfDetail.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
                    sfDetail.setCreateUserid(new Long(2));
                 sfDetail.setUpdateUserid(new Long(2));


                    sfDetail.setCreateTime(nowDate);
                    sfDetail.setUpdateTime(nowDate);
                    tSfFinalStatementDetailMapper.insert(sfDetail);  //***3  ("解约结算明细处理");
                    System.out.println("==================================================================998***3 end");

                    if (sfDetail.getDealType() == 1) { // 自己应退 pay
                        payCount += sfDetail.getAmount().doubleValue();
                    } else {  // 自己应收
                        recCount += sfDetail.getAmount().doubleValue();
                    }
                }
//
//
//            } catch (com.alibaba.fastjson.JSONException jsonException) {
//                sfDetail = new SfFinalStatementDetailEntity();
//                JSONObject parseObject = JSONObject.parseObject(json);
//                // 商户ID
//                sfDetail.setBusinessId(requestTerminalSfContractDto.getBusinessId());
//                // 解约协议Id
//                sfDetail.setTSfTerminationId(sfTerminationEntity.getId());
//                // 解约协议编号
//                sfDetail.setSfTerminationNo(sfTerminationEntity.getSfTerminationNo());
//                // 收房合同ID
//                sfDetail.setSfContractId(requestTerminalSfContractDto.getSfContractId());
//                // 收房合同编号
//                sfDetail.setSfContractNo(requestTerminalSfContractDto.getSfContractNo());
//                // 收付类型 1:应退 2：应收 json类型
//                sfDetail.setDealType(Integer.parseInt(parseObject.get("dealType").toString()));
//                // json 款项 押金水电等
//                sfDetail.setItemType(Integer.parseInt(parseObject.get("itemType").toString()));
//                // json 金额
//                sfDetail.setAmount(new BigDecimal(parseObject.get("amount").toString()));
//                // json 备注
//                sfDetail.setRemark(parseObject.get("detailRemark").toString());
//                // 共通
//                sfDetail.setDelFlg(false);
//                sfDetail.setCreateUserid(requestTerminalSfContractDto.getLoginUserId());
//                sfDetail.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
//                sfDetail.setCreateTime(nowDate);
//                sfDetail.setUpdateTime(nowDate);
//
//                sfFinalStatementDetailMapper.insert(sfDetail);   //***4   插入 解约结算明细
//                System.out.println("==================================================================998***4 end");
//                if (sfDetail.getDealType() == 1) { // 应退 pay
//                    payCount += sfDetail.getAmount().doubleValue();
//                } else {
//                    recCount += sfDetail.getAmount().doubleValue();
//                }
//
//
//            }
//
//
////			catchcatch   catch catch catch   catch catch catch catch   catchcatch catch catch   catch end
//
//
//
//            double total = recCount - payCount;// 收款-付款
//
//            logger.info(" 查看合计，如果不同进行修改");
//            if (total != requestTerminalSfContractDto.getFinalStatement().doubleValue()) {
//                sfDetail.setAmount(new BigDecimal(total + ""));
//                sfFinalStatementDetailMapper.updateById(sfDetail);  //***5  解约结算明细
//                System.out.println("==================================================================998***5 end");
//            }
//
//            logger.info(" 保存解约协议附件信息");
//            /**
//             * 附件保存： ① 业务对象ID,附件所属对应的业务数据ID，比如：合同/协议ID ②
//             * 附件所属区分,"10：收房合同，11：收房解约协议，20：出房合同，21：出房解约协议" ③ 附件类型
//             * ,"1:注册身份证，2：营业执照，3：租赁合同，4：客户身份证，5：收房合同
//             * 6：房产证，7：业主身份证，8：代理人身份证明，9：银行卡信息，10：委托书，99：其他"
//             */
//            // 业务对象ID
//            Long relationId = requestTerminalSfContractDto.getSfContractId();
//            // 附件所属区分
//            Integer relationType = AttachmentRelationTypeEnum.SFJYHT.getIndex();
//            // 保存解约合同
//            saveAttachement(relationId, relationType, AttachmentTypeEnum.JYHT.getIndex(),
//                    requestTerminalSfContractDto.getContractPhotos(), requestTerminalSfContractDto.getLoginUserId());
//            // 保存物业交割单
//            saveAttachement(relationId, relationType, AttachmentTypeEnum.WYJGD.getIndex(),
//                    requestTerminalSfContractDto.getPropertyDeliverys(), requestTerminalSfContractDto.getLoginUserId());
//            // 保存其他
//            saveAttachement(relationId, relationType, AttachmentTypeEnum.QT.getIndex(),
//                    requestTerminalSfContractDto.getOtherPhotos(), requestTerminalSfContractDto.getLoginUserId());


//
        System.out.println("更新收房合同");


        TSfContract sfContractEntity = tSfContractMapper  //***6  查找收房合同
                    .selectById(requestTerminalSfContractDto.getId());
            System.out.println("==================================================================998*** 6 end");
            // 共通
            sfContractEntity.setUpdateTime(nowDate);
            sfContractEntity.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
            // 合同状态
//            if (sfTerminationEntity.getTerminationType() != 1) {
//                sfContractEntity.setStatus(ContractStateEnum.TERMINATED.getIndex());// 3、已解约
//            } else {
//                sfContractEntity.setStatus(ContractStateEnum.ENDED.getIndex());// 4、已结束
//            }

        tSfContractMapper.updateById(sfContractEntity);   //***7  更新收房合同
            System.out.println("==================================================================998***7 end");


        System.out.println("更新付款计划 CwPaymentPlanEntity 更新pay_status");

            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("contract_id", sfContractEntity.getId());
//            columnMap.put("contract_type", ContractTypeEnum.SF.getIndex());
//
            List<TCwPaymentPlan> paymentPlan = tCwPaymentPlanMapper.selectByMap(columnMap);   //***8  查找付款计划
            System.out.println("==================================================================998***8 end");
            for (TCwPaymentPlan cwPaymentPlanEntity : paymentPlan) {
                // 款项
//                cwPaymentPlanEntity.setPayType(PaymentTypeEnum.JYJS.getIndex());
                // 共通
                cwPaymentPlanEntity.setUpdateUserid(cwPaymentPlanEntity.getCreateUserid());
                cwPaymentPlanEntity.setUpdateTime(nowDate);
                tCwPaymentPlanMapper.updateById(cwPaymentPlanEntity);  //***9  更新付款计划
                System.out.println("==================================================================998***9 end");
            }
//
//

        TbHouseInfo house = tbHouseInfoMapper.getHouseInfoByHouseId(requestTerminalSfContractDto.getHouseId());
            System.out.println("==================================================================998***9-2 end");
            house.setDelFlg(true);

        tbHouseInfoMapper.updateById(house);
            List<TbHouseInfo> roomListByHouseId = tbHouseInfoMapper
                    .getRoomListByHouseId(requestTerminalSfContractDto.getHouseId());
            System.out.println("==================================================================998***9-3 end");


//            for (RoomInfoEntity roomInfoEntity : roomListByHouseId) {
//                roomInfoEntity.setDelFlg(true);
//                tbRoomInfoMapper.update(roomInfoEntity);
//                System.out.println("==================================================================998***9-4 end");
//            }

//
//
////	==================================		=====================================================================if else   st
//
//
//
//
//            logger.info("生成新的付款计划");
        TSfContract contractEntity = tSfContractMapper.selectById(sfContractEntity.getId());//查询收房合同让下面使用  //***10    if,else中都用到
            System.out.println("==================================================================998***10 end");
//            if (total > 0) {     //if (total > 0)  st
//                // 收款计划   我收你钱
//                CwReceiptPlanEntity rec = new CwReceiptPlanEntity();    //&&&  装值实体3
//
//                String contractNo2 = "";
//
//
////				try {
////					contractNo = sequenceService.getSerialNumber(SerialType.SHOUKUANJIHUA);
////				} catch (Exception e) {
////					logger.info("-----收款计划编号获取失败-----");
////					throw e;
////				}
//
//
//                contractNo2 = "收款计划编号" + random;
//
//
//                // 收款计划编号
//                rec.setReceiptOrderNo(contractNo2);
//                // 商户ID
//                rec.setBusinessId(requestTerminalSfContractDto.getBusinessId().longValue());
//                // 收房合同ID
//                rec.setContractId(requestTerminalSfContractDto.getSfContractId());
//                // 收房合同单号
//                rec.setContractNo(requestTerminalSfContractDto.getSfContractNo());
//                // 合同类型：收房合同
//                rec.setContractType(ContractTypeEnum.SF.getIndex());
//                // 解约协议ID
//                rec.setTTerminationId(sfTerminationEntity.getId());
//                // 楼盘ID
//                rec.setPremiseId(infoByHouseId.getPremisesId().longValue());
//                // 小区
//                rec.setPremiseName(requestTerminalSfContractDto.getPremiseName());
//                // 业主ID
//                rec.setOwnerId(contractEntity.getOwnerId());
//                // 业主名称
//                rec.setOwnerName(contractEntity.getOwnerName());
//                // 收款类型
//                rec.setReceiptType(ReceiptTypeEnum.JYJS.getIndex());
//                // 收款状态
//                rec.setSkStatus(SkStatusEnum.WSK.getIndex());
//                // 账单类型
//                rec.setBillType(CollectionPlanZdType.TZBG.getIndex());
//                // 款项
//                rec.setItemType(BusinessCostTypesEnum.JIEYUEJIESUAN.getIndex());
//                // 其它款项
//                if (StringUtils.isNotBlank(requestTerminalSfContractDto.getOtherItemName())) {
//                    rec.setOtherItemName(requestTerminalSfContractDto.getOtherItemName());
//                }
//                // 支付金额（应收金额）合计
//                rec.setPaymentAmount(new BigDecimal(Math.abs(total) + ""));
//                // 租金 //收房合同租金
//                rec.setRentalPrice(sfContractEntity.getMonthRent());
//                // 账期开始日
//                rec.setPaymentDaysBegin(nowDate);
//                // 操作人
//                // rec.setOperationUser("张三");
//                rec.setOperationUser(requestTerminalSfContractDto.getLoginUser().getUsername());// 操作人
//                // 备注
//                rec.setRemark(requestTerminalSfContractDto.getRemark());
//                // 共通
//                rec.setDelFlg(false);
//                rec.setCreateTime(nowDate);
//                rec.setUpdateTime(nowDate);
//                rec.setCreateUserid(requestTerminalSfContractDto.getLoginUserId());
//                rec.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
//
//
//                cwReceiptPlanMapper.insert(rec);  //***  新增付款计划
//
//                System.out.println("==================================================================998***11 end");
//
//            } else if (total < 0) {       //if (total > 0)  end        //if (total < 0)  st
//
//                // 付款计划
//                CwPaymentPlanEntity pay = new CwPaymentPlanEntity();  //&&&  装值实体4
//
//
//
//
//
//                String contractNo3 = "";
////				try {
////					contractNo = sequenceService.getSerialNumber(SerialType.FUKUANJIHUA);
////				} catch (Exception e) {
////					logger.info("-----付款计划编号获取失败-----");
////					throw e;
////				}
//
//
//                contractNo3 = "付款单号" + random;
//
//
//                // 付款单号
//                pay.setPayOrderNo(contractNo3);
//                // 商户ID
//                pay.setBusinessId(requestTerminalSfContractDto.getBusinessId());
//                // 合同ID
//                pay.setContractId(requestTerminalSfContractDto.getSfContractId());
//                // 合同编号
//                pay.setContractNo(requestTerminalSfContractDto.getSfContractNo());
//                // 合同类型
//                pay.setContractType(ContractTypeEnum.SF.getIndex());
//                // 解约协议ID
//                pay.setTTerminationId(sfTerminationEntity.getId());
//                // 楼盘ID
//                pay.setPremiseId(requestTerminalSfContractDto.getPremiseId());
//                // 小区(使用楼盘名)
//                pay.setPremiseName(requestTerminalSfContractDto.getPremiseName());
//                // 业主ID
//                pay.setOwnerId(contractEntity.getOwnerId());
//                // 业主名称
//                pay.setOwnerName(contractEntity.getOwnerName());
//                // 付款类型
//                pay.setPayType(PaymentTypeEnum.JYJS.getIndex());
//                // 付款状态
//                pay.setPayState(PayStatusEnum.WFK.getIndex());
//                // 账单类型
//                pay.setBillType(CollectionPlanZdType.TZBG.getIndex());
//                // 款项
//                pay.setItemType(BusinessCostTypesEnum.JIEYUEJIESUAN.getIndex());
//                // 其它款项
//                if (StringUtils.isNotBlank(requestTerminalSfContractDto.getOtherItemName())) {
//                    pay.setOtherItemName(requestTerminalSfContractDto.getOtherItemName());
//                }
//                // 支付金额（应付金额） 合计
//                pay.setPaymentAmount(new BigDecimal(Math.abs(total) + ""));
//                // 预定付款日期 nowdate
//                pay.setPayableDate(nowDate);
//                // 租金 //收房合同租金
//                pay.setRentalPrice(sfContractEntity.getMonthRent());
//                // 账期开始日
//                pay.setPaymentDaysBegin(nowDate);
//                // 操作人
//                // pay.setOperationUser("张三");
//                pay.setOperationUser(requestTerminalSfContractDto.getLoginUser().getUsername());// 操作人 loginusername
//                // 备注 //解约备注
//                pay.setRemark(requestTerminalSfContractDto.getRemark());
//                // 共通
//                pay.setDelFlg(false);
//                pay.setCreateTime(nowDate);
//                pay.setUpdateTime(nowDate);
//                pay.setCreateUserid(requestTerminalSfContractDto.getLoginUserId());
//                pay.setUpdateUserid(requestTerminalSfContractDto.getLoginUserId());
//
//
//
//                cwPaymentPlanMapper.insert(pay);   //***12   //新增付款计划
//                System.out.println("==================================================================998***12 end");
//
//                logger.info("terminalSfContract处理end===============================================99999888888...");
//
//            }   //if (total < 0)  end  //	==================================		=====================================================================if else   end
////        } else {     //	if (a == list.size())  end
////            logger.info("房源未解约，房产解约失败");
////            throw new BusinessException("房源未解约，房产解约失败");
////        }

    }
//	================================  ================================   ================================ ===================== ===========   endend


}
